<template>
    
    <div class="text-right "><el-date-picker style="width: 200px;" @change="onChangeDate" v-model="date" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期" /></div>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" :size="formSize" status-icon label-position="top">
        <h1 style="font-size: 2rem;text-align: center;color: #000;width: 100%;">施 工 日 记 </h1>
        <div class="text-right" style="color: #000;">日期：{{date}} </div>
        <el-table class="mt20" :data="tableData" border size="small" :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#606266' }" style="width: 100%;font-size: 14px;height: auto !important;margin: 0px;">
            <el-table-column prop="title" label="昼夜" align="center" />
            <el-table-column label="天气状况" align="center">
                <template #default="scope">
                    <div class="text-center" v-if="scope.$index == 0"><el-input class="no-border-input" v-model="ruleForm.day_weather" /></div>
                    <div class="text-center" v-else><el-input class="no-border-input" v-model="ruleForm.night_weather" /></div>
                </template>
            </el-table-column>
            <el-table-column label="风力" align="center">
                <template #default="scope">
                    <div class="text-center" v-if="scope.$index == 0"><el-input class="no-border-input" v-model="ruleForm.day_wind" /></div>
                    <div class="text-center" v-else><el-input class="no-border-input" v-model="ruleForm.night_wind" /></div>
                </template>
            </el-table-column>
            <el-table-column label="最低/最高温度" align="center">
                <template #default="scope">
                    <div class="text-center" v-if="scope.$index == 0"><el-input class="no-border-input" v-model="ruleForm.day_temperature" /></div>
                    <div class="text-center" v-else><el-input class="no-border-input" v-model="ruleForm.night_temperature" /></div>
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center">
                <template #default="scope">
                    <div class="text-center" v-if="scope.$index == 0"><el-input class="no-border-input" v-model="ruleForm.day_remarks" /></div>
                    <div class="text-center" v-else><el-input class="no-border-input" v-model="ruleForm.night_remarks" /></div>
                </template>
            </el-table-column>
        </el-table>
        <UniformDescriptions :column="5" border direction="vertical" >
            <el-descriptions-item class="custom-bg" label="现场施工记录" :span="5">
                <el-form-item>
                    <el-input class="no-border-input" v-model="ruleForm.work_content" type="textarea" :autosize="{ minRows: 2 }" />
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="技术质量安全情况记录" :span="5">
                <el-form-item >
                    <el-input class="no-border-input" v-model="ruleForm.quality_safety" type="textarea" :autosize="{ minRows: 2 }" />
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="材料、构件进场" :span="5">
                <el-form-item >
                    <el-input class="no-border-input" v-model="ruleForm.materials" type="textarea" :autosize="{ minRows: 2 }" />
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="尚待解决" :span="5">
                <el-form-item >
                    <el-input class="no-border-input" v-model="ruleForm.problems" type="textarea" :autosize="{ minRows: 2 }" />
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="5">
                <el-form-item >
                    <el-input class="no-border-input" v-model="ruleForm.remarks" type="textarea" :autosize="{ minRows: 2 }" />
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="现场照片" :span="5">
                <el-form-item >
                    <el-button type="primary" @click="onUpload" >上传</el-button>
                    <el-button :type="ruleForm.files ? 'primary' : ''" @click="onShowFile(ruleForm.files)" >查看</el-button>
                </el-form-item>
            </el-descriptions-item>
        </UniformDescriptions>
    </el-form>
    <el-divider />
    <div class="text-center">
        <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="loading"> 保存 </el-button>
        <component :is="applyButton" model = "Diary" source = "Diary" type = "apply" price="0" :id = ruleForm.id />
        <component :is="applyRevoke" model = "Diary" source = "Diary" :id = ruleForm.id />
        <el-button @click="onDay('prev')" :loading="loading"> 上一天 </el-button>
        <el-button type="success" @click="onDay('next')" :loading="loading"> 下一天 </el-button>
    </div>

    <el-dialog v-model="showUpload" title="文件">
        <component :is="uploadMoreImg" :data="uploadData" :fileList="fileList" @saveUpload="saveUpload" />
    </el-dialog>

    <el-dialog v-model="isShowFile" title="文件" width="80%" @close="onCloseFile">
        <component :is="showFileArr" :data="files"/>
    </el-dialog>

</template>
  
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElLoading, ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import http from '../../../util/request';
import UniformDescriptions from '@/components/UniformDescriptions.vue'
import uploadMoreImg from '@/components/uploadMoreImg.vue'
import applyButton from "@/components/applyButton.vue";
import applyRevoke from "@/components/applyRevoke.vue";
import showFileArr from '@/components/showFileArr.vue'
import dayjs from 'dayjs'
const showUpload = ref<boolean>(false)
let uploadData:any = ref({prefix:'scene/'})
let fileList:any = ref([]);
const files = ref<string[]>([])
const isShowFile = ref<boolean>(false)

const tableData = ref<any>([
    {
        weather:'',
        temperature:'',
        wind:'',
        remarks:'',
        title:'白天',
    },
    {
        weather:'',
        temperature:'',
        wind:'',
        remarks:'',
        title:'夜间',
    },
])
const loading = ref<boolean>(false)
const week = ref<string>('')
const date = ref<string>('')
interface RuleForm {
    id:number
    date: string
    day_weather:string
    day_temperature:string
    day_wind:string
    night_weather:string
    night_temperature:string
    night_wind:string
    work_content: string
    progress: string
    quality_safety: string
    materials: string
    problems: string
    day_remarks:string
    night_remarks:string
    remarks: string
    files: string
}

const formSize = ref<ComponentSize>('large')
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<RuleForm>({
    id:0,
    date: '',
    day_weather:'/',
    day_temperature:'/',
    day_wind:'/',
    night_weather:'/',
    night_temperature:'/',
    night_wind:'/',
    work_content: '/',
    progress: '/',
    quality_safety: '/',
    materials: '/',
    problems: '/',
    day_remarks:'/',
    night_remarks:'/',
    remarks: '/',
    files: '',
})


const getData = () => {
    ruleForm.value.id = 0
    ruleForm.value.date = ''
    ruleForm.value.day_weather = ''
    ruleForm.value.day_temperature = ''
    ruleForm.value.day_wind = ''
    ruleForm.value.night_weather = ''
    ruleForm.value.night_temperature = ''
    ruleForm.value.night_wind = ''
    ruleForm.value.work_content = ''
    ruleForm.value.progress = ''
    ruleForm.value.quality_safety = ''
    ruleForm.value.materials = ''
    ruleForm.value.problems = ''
    ruleForm.value.day_remarks = ''
    ruleForm.value.night_remarks = ''
    ruleForm.value.remarks = ''
    ruleForm.value.files = ''
    
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    
    http.get('/construction/diary/'+date.value).then((response:any)=>{
        loading.close()
        if(response.data.data){
            ruleForm.value = response.data.data
            tableData.value = [
                {
                    weather:ruleForm.value.day_weather,
                    temperature:ruleForm.value.day_temperature,
                    wind:ruleForm.value.day_wind,
                    remarks:ruleForm.value.day_remarks,
                    title:'白天',
                },
                {
                    weather:ruleForm.value.night_weather,
                    temperature:ruleForm.value.night_temperature,
                    wind:ruleForm.value.night_wind,
                    remarks:ruleForm.value.night_remarks,
                    title:'夜间',
                },
            ];
        }
    })
}


const onDay = (type:string) => {
    const res = new Date(date.value);
    if(type == 'prev'){
        res.setDate(res.getDate() - 1);
    }else{
        res.setDate(res.getDate() + 1);
    }
    date.value = res.toISOString().split('T')[0]
    getData()
}

const rules = reactive<FormRules<RuleForm>>({
    date: [
        { required: true, message: '请输入选择日期', trigger: 'blur' },
    ],
})


const onChangeDate = (data:string) => {
    date.value = data
    getData()
}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            loading.value = true
            ruleForm.value.date = date.value
            let request:any = null
            if(ruleForm.value.id){
                request = http.patch('/construction/diary',ruleForm.value)
            }else{
                request = http.put('/construction/diary',ruleForm.value)
            }
            request.then((response:any)=>{
                loading.value = false
                if(response.data.code != 200){
                    ElMessage.error(response.data.msg);
                    return
                }
                ElMessage.success(response.data.msg);
                getData()
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const getWeek = () => {
    const specificDate = new Date(); // 注意：月份是从0开始的（0=一月，5=六月）
    const dayOfWeek = specificDate.getDay();
    const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
    week.value = weekdays[dayOfWeek]
}

const onUpload = () => {
    fileList.value = []
    uploadData.value.file = ruleForm.value.files
    if(ruleForm.value.files){
        let f:any = ruleForm.value.files.split(',')
        f.forEach((e:any) => {
            fileList.value.push({name:e,url:e})
        });
    }
    
    showUpload.value = true
}

const saveUpload = (data:string[]) => {
    ruleForm.value.files = data.join(',');
    showUpload.value = false
}

const onCloseFile = () => {
    files.value = []
}

const onShowFile = (file:string) => {
    if(files){
        files.value = file.split(',')
    }
    isShowFile.value = true
}

onMounted(()=>{
    date.value = dayjs().format('YYYY-MM-DD')
    getWeek()
    getData()
})

</script>
<style scoped>
.el-form{margin:0px auto;height: calc(100vh - 25vh);overflow-y: scroll;padding: 15px;}
.el-table .cell {font-size: .7rem !important;padding: 0px 3px !important;}
/* 全局移除 el-input 边框 */
.no-border-input {
/* 覆盖 Element Plus 的 CSS 变量 */
	--el-input-border-color: transparent;
	--el-input-focus-border-color: transparent;
	--el-input-hover-border-color: transparent;
}

/* 配合移除阴影 */
:deep(.no-border-input .el-input__inner) {
	box-shadow: none;
}
</style>
